import { cloneDeep,uniqBy } from 'lodash'
import { parse } from 'qs'
import { message } from 'antd'
import config from '../../../../config/config'
import { Link, hashHistory } from 'dva/router'
import {
  getroleList,
  updateUser,
  queryAllAddress,
  getUserDetail,
  queryAddressList,
  createUser,
} from './userAddServ'

const defultState = {
  btnLoading: false,
  requestUrl: '',
  roleList: [],
  test: '1',
  detail: {},
  sellerList: [],
  areaList: [],
  addressList:[],
  selectItem: [],
  userInfor: {},
  role: [],
  accountId: '',
  query: {
    accountId: '',
    permissionRoleIds: [],
    productIds: [],
  }
}

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({pathname, query}) => {
        if ('' + tmpModule.pathname === '' + pathname) {
          // 执行业务操作
          let {accountId} = query
          //每次进来页面更新数据 重置state
          dispatch({type: 'updateStore', payload: cloneDeep(defultState)})
          dispatch({type: 'updateStore', payload: {requestUrl: 'admin/permissionAdmin/list',accountId}})
          dispatch({type: 'getAreaList', payload: {}})
          dispatch({type: 'fetchRoleList', payload: {}})
          // dispatch({ type: 'getAddressList', payload: {} })
          // dispatch({type:'updateStore',payload: {}})
        }
      })
    }
  },
  
  effects: {
    * getAreaList ({payload}, {put, call, select}) {
      try {
        const data = yield call(queryAllAddress, {})
        if (data.success) {
          let areaList = []
          //澳门与北京只有两级
          let arr = [data.data[0]]
          let attr = [data.data[data.data.length - 1]]
          data.data[0] = {
            label: '北京',
            value: '110100',
            children: arr
          }
          data.data[data.data.length - 1] = {
            label: '澳门',
            value: '820000',
            children: attr
          }
          areaList = data.data
          
          yield put({type: 'updateStore', payload: {areaList}})
        }
      } catch (e) {
      
      }
    },
    
    * fetchRoleList ({payload}, {put, call, select}) {
      try {
        let {data, success} = yield call(getroleList, parse(payload))
        if (success) {
          let arr = (data instanceof Array) ? arr = data.map(item => {
            return {value: item.permissionRoleId, label: item.name,select:true}
          }) : []
          let {detail} = yield select(d => d[tmpModule.namespace])
          // console.log(detail.roleList)
          let attr  = (detail.roleList instanceof Array) ? detail.roleList.map(item => {
            return {value: item.permissionRoleId, label: item.name}
          }):[]
          arr.concat(attr).forEach((item,idx) => {
            console.log(item,'item')
            attr.forEach((val,index)=>{
              // console.log(item.value !=val.value)
              if(item.value !=val.value){
                // console.log(val)
                arr.push({...val,select:false})
              }
            })
          });
          let newArr=uniqBy(arr,'value')
          console.log(newArr)
          yield put({type: 'updateStore', payload: {roleList: newArr}})
        }
      } catch (e) {
        console.error(e)
      }
    },
    * save ({payload}, {put, select, call}) {
      let {query, detail,accountId} = yield select(d => d[tmpModule.namespace])
      query.endTime = query.endTime == "" ? null : query.endTime
      query.startTime = query.startTime == "" ? null : query.startTime
      detail.startTime = query.startTime;
      detail.endTime = query.endTime
      detail.permissionRoleIdList = query.permissionRoleIds
      console.log('query',detail)
      try {
        console.log('juese', query.permissionRoleIds.length)
        if (query.permissionRoleIds && query.permissionRoleIds.length == 0) {
          message.error('请选择角色')
        } else {
          yield put({type: 'updateStore', payload: {loading: true, btnLoading: true,}})
          let {data, success, msg} = yield call(createUser, detail)
          yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
          if (success) {
            message.success('创建成功').then(() => {
              hashHistory.push('/home/userList')
            })
          } else {
            message.error(msg)
          }
        }
        
      } catch (e) {
        console.log(e)
      }
    },
    * update ({payload}, {put, select, call}) {
      let {query, role, selectItem, detail,accountId} = yield select(d => d[tmpModule.namespace])
      
      query.accountId = accountId
      query.name = detail.name
      query.authenticationId = detail.authenticationId
      query.endTime=query.endTime==""?null:query.endTime
      query.startTime=query.startTime==""?null:query.startTime

      
      console.log('query',query)
      try {
        
        console.log('juese', query.permissionRoleIds.length)
        if (query.permissionRoleIds && query.permissionRoleIds.length == 0) {
          message.error('请选择角色')
        } else {
          yield put({type: 'updateStore', payload: {loading: true, btnLoading: true,}})
          let {data, success, msg} = yield call(updateUser, parse(query))
          yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
          if (success) {
            message.success('编辑成功').then(() => {
              hashHistory.push('/home/userList')
            })
          } else {
            message.error(msg)
          }
        }
        
      } catch (e) {
        console.log(e)
      }
    },
    
    * getDetail ({payload}, {put, select, call}) {
      try {
        let {data, success} = yield call(getUserDetail, parse(payload))
        let query = {
          accountId: '',
          permissionRoleIds: [],
          productIds: [],
        }
        let selectItem = []
        let detail = {}
        if (success) {
          //query.accountId = data.accountId
          detail = data
          selectItem = data.products
          console.log(data)
          if (data.roleList) {
            for (let i = 0; i < data.roleList.length; i++) {
              query.permissionRoleIds.push(data.roleList[i].permissionRoleId)
            }
          }
          if (data.products) {
            for (let i = 0; i < data.products.length; i++) {
              query.productIds.push(data.products[i].productId)
            }
          }
          console.log(selectItem)
          yield put({type: 'updateStore', payload: {query, detail, selectItem}})
          yield put({type: 'fetchRoleList', payload: {}})

        }
      } catch (e) {
        console.error(e)
      }
      
    },
    // 获取区域地址
    *getAddressList({ payload }, { put, call, select }) {
      let {modalObj,} = yield select(state => state[tmpModule.namespace])
      try {
        // debugger
        const { success, data=[] } = yield call(queryAddressList,{})
        
        if (success) {
          let addressList = []
          data.map((item,index)=>{
            addressList.push({
                id: item.regionId,
                name: item.regionName
              })
          })
          yield put({ type: 'updateStore', payload: { addressList } });
        }
      } catch (e) {
      }
    }
  },
  
  reducers: {
    updateStore (preState, action) {
      return {...preState, ...action.payload}
    }
  }
}

export default tmpModule
